/**
 * Created by Administrator on 2018/1/17.
 */
define(function(require, exports, module) {
    var $=require('zepto');
    s=require('./stock');
    api=require('api');
    cn=require('conment');
    pop=require('popup');
    lg=require('login');
    module.exports = {
        stockcode:cn.getQueryString('code')||'000001',
        tm :Math.pow(10, 3),
        timestamp: Date.parse(new Date()) / 1000,
        type :"sz",

        data:{},
        intCode:cn.getQueryString('code'),
        history:JSON.parse(cn.getItem('history')),
        init:function () {
            var _this=this;
            lg.userInfo();
            function getNowFormatDate() {
                var date = new Date();
                var seperator1 = "-";
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                var currentdate = year + seperator1 + month + seperator1 + strDate;
                return currentdate;
            }
            if(_this.intCode==null&&_this.history==null){
                _this.stockcode='000001'
            }else if(_this.intCode){
                _this.stockcode=_this.intCode
            } else if(_this.history.length>0){
                var c=Object.keys(_this.history)
                _this.stockcode=c[0]
            }
            _this.data.stockID=_this.stockcode;
            _this.data.stockType=_this.type;
            _this.data.time=parseInt(_this.timestamp);
            _this.data.hq=eval('"hq_str_'+_this.type+_this.stockcode+'"');
            _this.data.day=""+getNowFormatDate();
            _this.data.isHqReload=eval("true");


            //菜单
            _this.data.menu=[];

            _this.data.menu.push({name:"minute",	title:"分时"});
            _this.data.menu.push({name:"dayK",	title:"日K"});

            //默认加载
            _this.data.default="minute";
            stock.load(_this.data);

            _this.chooseStockInit();
            _this._temslist();

            $(document).on('click',function (e) {
                var target  = $(e.target);
                if(target.closest(".change-stock").length == 0){
                    $('#search_cue').hide();
                }
            });
            $('#searchConfirm').on('click',function () {
                if($('#search_cue').is(":hidden")){
                    return
                }
                if($('#tbody tr').length>0){
                    var code=$('#tbody tr').eq(0).data('code');
                    window.location.href=cn.GetUrlRelativePath()+'?code='+code;
                    // $('#stock-canvas').children().remove();
                    // $('#search_cue').hide();
                    // _this.data.stockID=code;
                    // stock.load(_this.data);
                    // _this._temslist();
                }else{
                    cn.alert('请输入查询的股票')
                }
            })
        },
        //搜索
        chooseStockInit:function () {
            var stockChange = $(".play-area").find(".search-table"),_this=this;

            $("#searchTxt").off().on("keyup focus", function (event) {

                var key = event.keyCode;
                //13是enter键，38是上键，40是下键
                if (key !== 38 && key !== 40 && key !== 13) {
                    if ($(this).val().length) {
                        var name = $(this).val();
                        _this.seach_stock(name)
                         //把字符串转换为小写
                    } else {
                       _this.seach_history() //调用搜索历史函数
                    }
                } else {
                    event.preventDefault();   //阻止事件
                    var base = $("#search_history, #search_cue").find("tbody:visible");
                    if (base.find("tr.active").length > 0) {
                        if (key === 38) {
                            // goUp(base);
                        } else if (key === 40) {
                            // goDown(base);
                        } else if (key === 13) {
                            // base.find("tr.active").trigger("click");   //触发点击事件
                        }
                    }
                }
                // console.log(6)
            })
        },
        seach_stock:function (n) {
            var _this=this;
            $('#search_cue').show();
            cn.Ajax(api.seach,{
                keyword:n
            },function(d){
                // $('#quickQuery_list').empty();
                var arr=new Array(),list=d.list;
                $.each(list,function(i,l,array){
                   arr.push('<tr data-name="'+l.name+'" data-code="'+l.code+'" data-initial="'+l.initial+'" ><td>'+l.name+'</td><td>'+l.code+'</td><td>'+l.initial+'</td></tr>');
                });
                $('#tbody').html(arr.join(''));
                var host=new Array();
                $('#tbody tr').on('click',function () {
                    var history=JSON.parse(cn.getItem('history'))||{};
                    var name=$(this).data('name');
                    var code=$(this).data('code');
                    var initial=$(this).data('initial');
                    // if (!!window.ActiveXObject || "ActiveXObject" in window){
                    //     host ={[code]:{
                    //             'name': name,
                    //             'code':code,
                    //             'initial':initial,
                    //         }};
                    //     var newHist=$.extend(history, host);//Object.assign(history,host);
                    //     cn.setItem('history', JSON.stringify(newHist));
                    // }
                    window.location.href=cn.GetUrlRelativePath()+'?code='+code;
                    // $('#stock-canvas').children().remove();
                    // $('#search_cue').hide();
                    // _this.data.stockID=code;
                    // stock.load(_this.data);
                    // _this._temslist();
                })
            },'post')
        },
        seach_history:function () {
            var _this=this;
            var history=_this.history;
            if(history==null)return
            $('#search_cue').show();
            var arr=new Array(),list=history;
            $.each(list,function(i,l,array){
                arr.push('<tr data-name="'+l.name+'" data-code="'+l.code+'" data-initial="'+l.initial+'" ><td>'+l.name+'</td><td>'+l.code+'</td><td>'+l.initial+'</td></tr>');
            });
            $('#tbody').html(arr.join(''));
            $('#tbody tr').on('click',function () {
                var code=$(this).data('code');
                window.location.href=cn.GetUrlRelativePath()+'?code='+code;
                // $('#stock-canvas').children().remove();
                // $('#search_cue').hide();
                // _this.data.stockID=code;
                // stock.load(_this.data);
                // _this._temslist();
            })
        },
        //right
        free:free?'10':'11',
        buyId:null,
        _temslist:function () {
            var price=parseFloat($('#astock-price span').text());
            var _this=this;
            if(!price){
                setTimeout(function () {
                    _this._temslist()
                },10)
            }else{
                var stockNum=price*100;
                var freeId=null,freeNum=0;
                cn.Ajax(api.items,{
                    type:_this.free,
                },function(d){
                    if(d.flag==1){
                        var arr=new Array(),preBuyCount=0,percentage=0;
                        var list=d.list;
                        $.each(list,function(i,l,array){
                            preBuyCount= Math.floor((l.amount / price) / 100)*100;
                            percentage = (preBuyCount * price / l.amount*100).toFixed(2);//使用率
                            arr.push('<li class="'+(preBuyCount<100?'disable ':'')+(l.type==10?'free':'')+'" data-ratePre="'+l.ratePre+'" data-amountdelay="'+l.amountDelay+'" data-bond="'+l.bond+'" data-id="'+l.id+'" data-amount="'+l.amount+'" data-disable="'+(preBuyCount<100?'true':'false')+'">'+l.amountStr+'</li>');
                        });
                        $('#buy_price_ul').html(arr.join(''));

                        $('#buy_price_ul li').on('click',function () {
                            var amount=parseFloat($(this).data('amount'));
                            var buyCount=Math.floor((amount / price) / 100)*100;
                            freeNum=buyCount;
                            if($(this).data('disable'))return false
                            $(this).addClass('active').siblings('li').removeClass('active');
                            $('#preBuyCount').text(buyCount);
                            $('#percentage').text((buyCount * price / amount*100).toFixed(2));
                            $('#ratePre').text($(this).data('ratepre')+'元')
                            $('#bond').text($(this).data('bond')+'元');
                            if($(this).data('amountDelay')){
                                $('.amountDelay').show()
                                $('#amountDelay').text($(this).data('amountDelay')+'元/天');
                            }

                        });
                        var lilength=$('#buy_price_ul li.disable:last');
                        if(lilength.length<1){
                            $('#buy_price_ul li:eq(0)').click()
                        }else{
                            $('#buy_price_ul li.disable:last').next().click();
                        }



                    }else{
                        cn.alert(d.message)
                    }
                },'post');


                $("#btn_buy").on('click',function () {
                    var id=$('#buy_price_ul li.active').data('id');
                    if(_this.free==10){
                        if(freeNum<100)return cn.alert('超出免费策略金额，请更换股票')
                        if(!id)return;
                    }else {
                        if(!id)return cn.alert('请选择金额');
                    }
                    if(!$('#agree_pro').is(":checked")&&_this.free!=10){
                        cn.alert('请先仔细阅读协议');
                        return false
                    }
                    $(this).addClass('link-btn').attr('disabled',true);
                    _this.buyId=null;
                    cn.Ajax(api.buy,{
                        itemId:id,
                        stock:_this.stockcode
                    },function(d){
                        $("#btn_buy").removeClass('link-btn').attr('disabled',false);
                        if(d.flag==1){
                            _this.buyId=d.data.id;
                            $('#investorHolderCode').text(d.data.investorHolderCode);
                            $('#dadangname').text(d.data.investorDisplayName);
                            $('#model-name').text(d.data.name);
                            $('#model-code').text(d.data.code);
                            $('#model-time').text(d.data.applyTimeStr);
                            $('#model-amount').text(d.data.amount);
                            $('#model-num').text(d.data.buyQuantityPlan);
                            $('#model-price').text(d.data.buyPricePlan);
                            $('#model-typeStr').text(d.data.typeStr);
                            $('#model-profitPercent').text(d.data.profitPercent*100+'%');
                            $('#model-lowPercent').text(d.data.lowPercent*100+'%');
                            $('#model-amountBond').text(d.data.amountBond);
                            $('#model-amountRate').text(d.data.amountRate);
                            if(d.data.amountDelay){
                                $('#model-amountDelay').text('延递费用:'+d.data.amountRate+'元/天');
                            }

                            pop.popup_html({
                                id:'#popup-buy',
                            })
                        }else if(d.flag==-100){
                            pop.popup_warning_msg({
                                text:d.message,
                                id:'#popup-p-error',
                            })
                        }else{
                            cn.alert(d.message)
                        }
                    },'post');
                });
                $("#popup-confirm-btn").click(function () {
                    _this.buyPay()
                });
            }
        },
        isBtn:true,
        buyPay:function () {
            var _this=this;
            if(!_this.buyId){
                pop.popup_err_msg({
                    id:'#popup-p-error',
                    text:'失败'
                })
            }
            if(!_this.isBtn)return;
            _this.isBtn=false;
            pop.popup_warning_msg({
                id:'#popup-p-error',
                text:'正在寻找搭档...',
            });
            cn.Ajax(api.buyPay,{
                id :_this.buyId,
            },function(d){
                _this.isBtn=true;
                if(d.flag==1){
                    pop.popup_success_msg({
                        text:d.message,
                        id:'#popup-p-error',
                        cBack:{
                            text:'确定',
                            callBack:function () {
                               window.location.href='/comview/sell.html'
                                return false;
                            }
                        },
                    })

                }else{
                    pop.popup_err_msg({
                        text:d.message,
                        id:'#popup-p-error',
                    })
                }
            },'post')
        },

    }

});